$(function () {
    show_admin_name();
    init_table();
    add_employee();
});

function show_admin_name() {
    $.ajax({
        url: '/admin-info',
        type: 'GET',
        dataType: 'JSON',
        success: function (data) {
            if (data.status) {
                $('#show-admin-name').text(data.result);
            } else {
                console.log('wrong');
                alert('读取管理员信息失败')
            }
        }
    });
}

function init_table() {
    $.ajax({
        url: '/users-list',
        type: 'get',
        dataType: 'JSON',
        success: function (data) {
            if (data.status) {
                var result_list = new Array(data.result);
                let is_odd = "odd";
                result_list.forEach((value, _idx, _arr) => {
                    value.forEach((sub_value, _sub_idx, _sub_arr) => {
                        // console.log(sub_value['name']);
                        $t_body = $(
                            `<tr class=${is_odd}>
                                <td>${sub_value['id']}</td>
                                <td>${sub_value['name']}</td>
                                <td>
                                    <button class="btn btn-danger btn-sm delete-button" uid="${sub_value['id']}">删除</button>
                                    <button class="btn btn-warning btn-sm edit-button" uid="${sub_value['id']}">编辑</button>
                                    <button class="btn btn-success btn-sm select-button" uid="${sub_value['id']}">查看</button>
                                </td>
                            </tr>`
                        );
                        $('#table-body').append($t_body);
                        if (is_odd == "odd") {
                            is_odd = "even";
                        } else {
                            is_odd = "odd";
                        }
                        // add eventlistener for button 
                    });
                });
                delete_employee();
                edit_employee();
                select_employee();
                select_user_shop_info();
            } else {
                alert('数据库读取失败！');
            }
        }
    });
}

function add_employee() {
    $('#add-button').click(() => {
        $('#add-Modal').modal('show');
    });
    $('#add-confirm').click(() => {
        if ($('#add-name').val() != '' && $('#add-job').val() != '') {
            $.ajax({
                url: '/admin-add-user',
                type: 'POST',
                dataType: 'JSON',
                data: $('#add-form').serialize(),
                success: function (data) {
                    if (data.status) {
                        $('#add-confirm').attr('class', 'btn btn-success');
                        $('#add-confirm').text('正在添加..');
                        setTimeout(function () {
                            $('#add-Modal').modal('hide');
                            location.reload();
                        }, 1500);
                    } else {
                        $('#add-confirm').attr('class', 'btn btn-danger');
                        $('#add-confirm').text('添加失败');
                    }
                }
            });
        } else {
            $('#add-confirm').attr('class', 'btn btn-danger');
            $('#add-confirm').text('请完善信息后重试');
        }
    });
}

function delete_employee() {
    $('.delete-button').click(function () {
        $.ajax({
            url: `/admin-delete-user?id=${$(this).attr('uid')}`,
            type: 'GET',
            dataType: 'JSON',
            success: function (data) {
                if (data.status) {
                    $(this).attr('class', 'btn btn-success');
                    $(this).text('正在删除..');
                    alert('删除成功');
                } else {
                    $(this).attr('class', 'btn btn-danger');
                    $(this).text('删除失败');
                }
                setTimeout(function () {
                    location.reload();
                }, 1500);   
            }
        })
    })
}

function edit_employee() {
    var target_id = undefined;
    $('.edit-button').click(function () {
        var now_td = $(this).parent().parent().find('td');
        $('#edit-id').val(now_td.eq(0).text());
        $('#edit-name').val(now_td.eq(1).text());
        target_id = $(this).attr('uid');
        $('#edit-Modal').modal('show');
        console.log(target_id);
    })
    $('#edit-confirm').click(function () {
        if ($('#edit-name').val() != '' && target_id != undefined) {
            // $('#edit-confirm').attr('class', 'btn btn-success');
            // $('#edit-confirm').text('更改成功，请稍后..');
            // setTimeout(function () {
            //     $('#edit-confirm').attr('class', 'btn btn-primary');
            //     $('#edit-confirm').text('更改');
            //     change_target.eq(0).text($('#edit-name').val());
            //     change_target.eq(1).text($('#edit-sex-options').val());
            //     change_target.eq(2).text($('#edit-job').val());
            //     change_target.eq(3).text($('#edit-is-attend-options').val());
            //     change_target = undefined;
            //     $('#edit-Modal').modal('hide');
            // }, 1500);
            $.ajax({
                url: `/admin-edit-user?id=${target_id}`,
                type: 'POST',
                dataType: 'JSON',
                data: $('#edit-form').serialize(),
                success: function (data) {
                    if (data.status) {
                        $('#edit-confirm').attr('class', 'btn btn-success');
                        $('#edit-confirm').text('更改成功，请稍后..');
                    } else {
                        $('#edit-confirm').attr('class', 'btn btn-danger');
                        $('#edit-confirm').text('更改失败');
                    }
                    setTimeout(function () {
                        location.reload();
                    }, 1500);
                }
            })
        } else {
            $('#edit-confirm').attr('class', 'btn btn-danger');
            $('#edit-confirm').text('请完善信息后重试');
        }
    });
}

function select_employee() {
    $('.select-button').click(function () {
        var now_td = $(this).parent().parent().find('td');
        $('#select-id').val(now_td.eq(0).text());
        $('#select-name').val(now_td.eq(1).text());
        $('#select-id').attr('readonly', 'readonly');
        $('#select-name').attr('readonly', 'readonly');
        $('#select-user-shop').attr("uid", $(this).attr("uid"));
        $('#select-Modal').modal('show');
    });
}

function select_user_shop_info() {
    $('#select-user-shop').click(function () {
        // var username = $(this).parent().prev().children().eq(0).children('input[type=text]').val();
        // console.log(username);
        var id = $(this).attr('uid');
        $.ajax({
            url: `/get-user-info?id=${id}`,
            type: 'get',
            dataType: 'json',
            success: function (data) {
                if (data.status) {
                    var result_list = new Array(data.result);
                    result_list.forEach((val, _idx, _arr) => {
                        val.forEach((sub_val, _sub_idx, _sub_arr) => {
                            $t_body = `
                                <tr>
                                    <td>${sub_val['username']}</td>
                                    <td>${sub_val['id']}</td>
                                    <td>${sub_val['name']}</td>
                                    <td>${sub_val['price']}</td>
                                </tr>
                            `
                            $('#table-body-user-info').append($t_body);
                        });
                    });
                } else {
                    alert('数据获取失败');
                }
            }
        });
        $('#select-Modal').modal('hide');
        $('#shop-Modal').modal('show');
        $('#user-shop-name').text(username);
    });
}